# ！ /usr/bin/python3
# -*- coding:utf-8 -*-
# @Author:Peng Cao
# @File: 09img_图像轮廓.py
# @Software: PyCharm
import cv2.cv2 as cv
import matplotlib.pyplot as plt
import numpy as np


def img_contours():
    """
    给图像画轮廓
    :return:
    """
    img = cv.imread('./data/contours.png')
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # 将原始图片转换为灰度模式
    thresh, new_img = cv.threshold(src=img_gray, thresh=127, maxval=255, type=cv.THRESH_BINARY)  # 阈值操作
    cts, new_img2 = cv.findContours(image=new_img, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE)  # 获取轮廓值
    draw_img = img.copy()  # 避免drawContours后改变原来图像
    img_with_contours = cv.drawContours(image=draw_img, contours=cts, contourIdx=-1, color=(255, 0, 255), thickness=2)
    cv.imshow("img_with_contours", img_with_contours)
    cv.waitKey(0)
    cv.destroyAllWindows()
    return cts, img_with_contours


def cal_contours():
    """
    轮廓计算
    :return:
    """
    img = cv.imread('./data/contours.png')
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # 将原始图片转换为灰度模式
    thresh, new_img = cv.threshold(src=img_gray, thresh=127, maxval=255, type=cv.THRESH_BINARY)  # 阈值操作
    cts, new_img2 = cv.findContours(image=new_img, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE)  # 获取轮廓值
    img_with_cts = cv.drawContours(image=img.copy(), contours=cts, contourIdx=-1, color=(0, 0, 255), thickness=2)
    cv.imshow("img_with_cts", img_with_cts)
    ct0 = cts[6]  # 获取一个轮廓
    area = cv.contourArea(ct0)  # 计算轮廓面积
    print(f"轮廓的面积是：{area}")
    length = cv.arcLength(curve=ct0, closed=True)  # 计算周长
    print(f"轮廓的周长是：{length}")
    x, y, w, h = cv.boundingRect(ct0)  # 获取矩形轮廓的位置：x，y矩形轮廓起点坐标，w,h矩形轮廓宽，高
    img_with_rectangle = cv.rectangle(img=img, pt1=(x, y), pt2=(x + w, y + h), color=(0, 0, 255), thickness=2)
    cv.imshow("img_with_rectangle", img_with_rectangle)
    img_with_circle = cv.circle(img=img, center=(200, 200), radius=100, color=(0, 0, 255), thickness=2)
    cv.imshow("img_with_circle", img_with_circle)
    cv.waitKey(0)
    cv.destroyAllWindows()
    return img_with_rectangle


def app_contours():
    """
    轮廓近似
    :return:
    """
    img = cv.imread('./data/contours2.png')
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # 将原始图片转换为灰度模式
    thresh, new_img = cv.threshold(src=img_gray, thresh=127, maxval=255, type=cv.THRESH_BINARY)  # 阈值操作
    cts, new_img2 = cv.findContours(image=new_img, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE)  # 获取轮廓值
    epsilon = 0.1 * cv.arcLength(cts[0], True)  # 计算比较值
    ct_new = cv.approxPolyDP(curve=cts[0], epsilon=epsilon, closed=True)  # 计算近似后端轮廓值
    draw_img = img.copy()  # 避免drawContours后改变原来图像
    img_with_contours = cv.drawContours(image=draw_img, contours=[ct_new], contourIdx=-1, color=(255, 0, 255), thickness=2)
    cv.imshow("img_with_contours", img_with_contours)
    cv.waitKey(0)
    cv.destroyAllWindows()
    return img_with_contours


if __name__ == '__main__':
    # img_contours()
    cal_contours()
    # app_contours()
